package com.gexiaobao.pigeon.ui.fragment.login

import android.os.Build
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.text.style.UnderlineSpan
import android.view.View
import androidx.core.content.ContextCompat
import androidx.fragment.app.setFragmentResult
import androidx.lifecycle.lifecycleScope
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.ext.Constant
import com.gexiaobao.pigeon.app.ext.countDownCoroutines
import com.gexiaobao.pigeon.app.ext.initClose
import com.gexiaobao.pigeon.app.ext.showMessage
import com.gexiaobao.pigeon.app.model.param.GetVerCodeParams
import com.gexiaobao.pigeon.app.model.param.RegisterParams
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.databinding.FragmentRegisterBinding
import com.gexiaobao.pigeon.ui.activity.ActivityPrivacyAndService
import com.gexiaobao.pigeon.viewmodel.LoginViewModel
import com.lljjcoder.Interface.OnCityItemClickListener
import com.lljjcoder.bean.CityBean
import com.lljjcoder.bean.DistrictBean
import com.lljjcoder.bean.ProvinceBean
import com.lljjcoder.citywheel.CityConfig
import com.lljjcoder.style.citypickerview.CityPickerView
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.startActivity
import me.jessyan.autosize.internal.CustomAdapt
import java.util.regex.Matcher
import java.util.regex.Pattern

/**
 * @Author      : hxw
 * @Date        : 2023/5/31 11:24
 * @Describe    :
 */
class RegisterFragment : BaseFragment<LoginViewModel, FragmentRegisterBinding>(), CustomAdapt {

    private val mPicker = CityPickerView()
    private var isCodeLogin: Boolean = false

    override fun initView(savedInstanceState: Bundle?) {
        isCodeLogin = requireArguments().getBoolean("isCodeLogin")
        mDatabind.includeBar.toolbar.initClose(getString(R.string.register)) {
            setFragmentResult("requestIsCode", Bundle().apply {
                putBoolean("isCodeLogin", isCodeLogin)
            })
            nav().navigateUp()
        }
        mDatabind.viewmodel = mViewModel
        mViewModel.getVerificationCode.set(getString(R.string.Get_the_verification_code))
        initCityData()
        initSpanText()
    }

    private fun initSpanText() {
        val clickSpan: ClickableSpan = object : ClickableSpan() {
            override fun onClick(widget: View) {
                startActivity<ActivityPrivacyAndService>("type" to "1")
            }

            override fun updateDrawState(ds: TextPaint) {
                ds.isUnderlineText = false
            }
        }

        val clickSpanService: ClickableSpan = object : ClickableSpan() {
            override fun onClick(widget: View) {
                startActivity<ActivityPrivacyAndService>("type" to "2")
            }

            override fun updateDrawState(ds: TextPaint) {
                ds.isUnderlineText = false
            }
        }

        val spannable = SpannableStringBuilder(getString(R.string.have_read_and_agree))
        /** 这个一定要记得设置，不然点击不生效 */
        mDatabind.tvUserPolicy.movementMethod = LinkMovementMethod.getInstance()
        /** 设置文字的前景色 */
        spannable.setSpan(clickSpanService, 7, 15, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        spannable.setSpan(
            ForegroundColorSpan(ContextCompat.getColor(requireContext(), R.color.colorPrimary)),
            7,
            15,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        spannable.setSpan(clickSpan, 16, spannable.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        spannable.setSpan(
            ForegroundColorSpan(ContextCompat.getColor(requireContext(), R.color.colorPrimary)),
            16,
            spannable.length,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        mDatabind.tvUserPolicy.text = spannable


    }

    private fun initCityData() {
        val cityConfig = CityConfig.Builder().build()
        cityConfig.title = getString(R.string.elect_the_area)
        cityConfig.titleTextSize = 20
        cityConfig.confirmTextSize = 18
        cityConfig.cancelTextSize = 18
        cityConfig.titleTextSize = 18
        cityConfig.visibleItems = 8
        cityConfig.defaultProvinceName = getString(R.string.shandong_province)//默认显示的省份
        cityConfig.defaultCityName = getString(R.string.qingdao_city)
        cityConfig.customItemLayout = R.layout.item_city
        cityConfig.customItemTextViewId = R.id.item_city_name_tv
        mPicker.init(context)
        mPicker.setConfig(cityConfig)

        mPicker.setOnCityItemClickListener(object : OnCityItemClickListener() {
            override fun onSelected(
                province: ProvinceBean?,
                city: CityBean?,
                district: DistrictBean?
            ) {
                super.onSelected(province, city, district)
                mViewModel.address.set(province.toString() + "-" + city + "-" + district)
            }
        })
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.forgetCommit, mDatabind.registerVerifyCodeSend, mDatabind.ivChooseAddress) {
            when (it.id) {
                R.id.forget_commit -> {
                    register()
                }

                R.id.register_verify_code_send -> {
                    countDownCode()
                }

                R.id.ivChooseAddress -> {
                    mPicker.showCityPicker()
                }
            }
        }
    }

    private fun countDownCode() {
        val body = GetVerCodeParams(mViewModel.phoneNum.get(), 1)
        when {
            mViewModel.phoneNum.get().isEmpty() -> showMessage(resources.getString(R.string.user_mobile_number))
            !Util.isTelPhoneNumber(mViewModel.phoneNum.get()) -> showMessage(resources.getString(R.string.user_phone_number_wrong))
            else -> {
                //开启倒计时60s
                job = countDownCoroutines(60, {
                    mViewModel.getVerificationCode.set("${it}s")
                }, {
                    mViewModel.getVerificationCode.set(getString(R.string.Get_the_verification_code))
                }, lifecycleScope)
                mViewModel.getVerCode(body)
            }
        }
    }

    private fun register() {
        val limitEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]"
        val pattern: Pattern = Pattern.compile(limitEx)
        val m: Matcher = pattern.matcher(mViewModel.username.get())
        mViewModel.username.set(mViewModel.username.get())
//        mViewModel.userRealMame.set(mViewModel.userRealMame.get())
//        mViewModel.IDNumber.set(mViewModel.IDNumber.get())
        mViewModel.password.set(mViewModel.password.get())
        mViewModel.password2.set(mViewModel.password2.get())
        mViewModel.phoneNum.set(mViewModel.phoneNum.get())
        mViewModel.verificationCode.set(mViewModel.verificationCode.get())
        val body = RegisterParams(
            mViewModel.username.get().trim(),//用户名
            mViewModel.password.get(),//密码
            mViewModel.phoneNum.get(),//手机号
            1,//性别
            4,//写死类型
            "",
//            mViewModel.IDNumber.get(),//身份证
            mViewModel.verificationCode.get(),//验证码
//            mViewModel.userRealMame.get().trim(),//真实姓名
            "",
            0,//头像
            0,//背景不传
            mViewModel.address.get(),//地址
            mViewModel.detailAddress.get().trim(),//详细地址
            0//暂时没用
        )
        when {
            !mDatabind.checkUserPolicy.isChecked -> RxToast.showToast(getString(R.string.read_user_service))
            mViewModel.username.get()
                .isEmpty() -> showMessage(resources.getString(R.string.user_name))

            m.find() -> showMessage(resources.getString(R.string.user_name_no_pass))

            mViewModel.password.get()
                .isEmpty() -> showMessage(resources.getString(R.string.user_password))

            mViewModel.password2.get()
                .isEmpty() -> showMessage(resources.getString(R.string.user_repeat_password))

            mViewModel.phoneNum.get()
                .isEmpty() -> showMessage(resources.getString(R.string.user_mobile_number))

            !Util.isTelPhoneNumber(mViewModel.phoneNum.get()) -> showMessage(resources.getString(R.string.user_phone_number_wrong))
            mViewModel.verificationCode.get()
                .isEmpty() -> showMessage(resources.getString(R.string.user_verification_code))

            mViewModel.verificationCode.get().length != 6 -> showMessage(resources.getString(R.string.user_verification_code_wrong))
            mViewModel.password.get() != mViewModel.password2.get() -> showMessage(
                resources.getString(
                    R.string.user_password_not_alike
                )
            )

            else ->
                mViewModel.register(body)
        }
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.mResultRegister.observe(viewLifecycleOwner) {
            if (it.isSuccess) {
                RxToast.showToast(getString(R.string.registered_successfully))
                setFragmentResult("requestIsCode", Bundle().apply {
                    putBoolean("isCodeLogin", false)
                })
                nav().navigateUp()
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }

        mViewModel.verCodeResult.observe(viewLifecycleOwner) {
            if (it.isSuccess) {
                RxToast.showToast(getString(R.string.send_successfully))
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
    }

    override fun isBaseOnWidth(): Boolean {
        return false//按照宽度进行适配
    }

    override fun getSizeInDp(): Float {
        return when (Build.MANUFACTURER) {
            "realme", "vivo", "OPPO" -> {
                Constant.LANDSCREENFLOAT
            }

            "HUAWEI" -> {
                Constant.LANDSCREENFLOATHW
            }

            else -> {
                Constant.LANDSCREENFLOATS
            }
        }
    }

}